import React, { useState, useRef, useImperativeHandle, forwardRef } from 'react';
import { Divider, Form } from 'antd';
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table';
interface ItemInfoProps {
  ref?: any;
  onChange?: (list: any[]) => void;
}
const ItemInfo: React.FC<ItemInfoProps> = forwardRef((props, ref) => {
  const { onChange } = props;

  const actionRef = useRef<ActionType>();
  const [editForm] = Form.useForm();
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<any>[] = [
    {
      title: '物品名称',
      dataIndex: 'goods_name',
      align: 'center',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '登记时间',
      dataIndex: 'register_time',
      valueType: 'dateTime',
      width: 180,
      align: 'center',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '租赁周期',
      dataIndex: 'lease_cycle',
      valueType: 'select',
      valueEnum: {
        H: '按小时',
        D: '按天',
      },
      width: 100,
      align: 'center',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '周期长度',
      dataIndex: 'cycle_num',
      valueType: 'digit',
      align: 'right',
      fieldProps: (form, record) => {
        return {
          // precision: 0,
          // min: 1,
          style: {
            width: '100%',
          },
          onChange: (value: any) => {
            const item = form.getFieldsValue()[record.rowKey as string];
            if (item.goods_num > 0 && item.goods_price > 0 && value > 0) {
              item['goods_total_price'] =
                Number(item.goods_num * value * parseFloat(item.goods_price || 0)).toFixed(2);
            }
            form.setFieldsValue({ [record.rowKey || '']: item });
          },
        };
      },
      width: 100,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
          {
            validator: (_, value) => {
              if (value <= 0) {
                return Promise.reject(new Error('不能为0'));
              }
              return Promise.resolve();
            },
            message: '周期长度不能为0',
          },
        ],
      },
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right',
      fieldProps: (form, record) => {
        return {
          precision: 2,
          style: {
            width: '100%',
          },
          onChange: (value: any) => {
            const item = form.getFieldsValue()[record.rowKey as string];
            if (item.goods_num > 0 && item.cycle_num > 0 && value > 0) {
              item['goods_total_price'] = Number(item.goods_num * value * item.cycle_num).toFixed(2);
            }
            form.setFieldsValue({ [record.rowKey || '']: item });
          },
        };
      },
      width: 120,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
          {
            validator: (_, value) => {
              if (value <= 0) {
                return Promise.reject(new Error('不能为0'));
              }
              return Promise.resolve();
            },
            message: '单价不能为0',
          },
        ],
      },
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      align: 'right',
      fieldProps: (form, record) => {
        return {
          precision: 0,
          // min: 1,
          style: {
            width: '100%',
          },
          onChange: (value: any) => {
            console.log(form.getFieldsValue()[record.rowKey as string]);
            const item = form.getFieldsValue()[record.rowKey as string];
            if (item.goods_price > 0 && item.cycle_num > 0 && value > 0) {
              item['goods_total_price'] = Number(item.goods_price * value * item.cycle_num).toFixed(2);
            }
            form.setFieldsValue({ [record.rowKey || '']: item });
          },
        };
      },
      width: 100,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
          {
            validator: (_, value) => {
              if (value <= 0) {
                return Promise.reject(new Error('不能为0'));
              }
              return Promise.resolve();
            },
            message: '数量不能为0',
          },
        ],
      },
    },
    {
      title: '价格',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      fieldProps: {
        precision: 2,
        style: {
          width: '100%',
        },
        readOnly: true,
        placeholder: ''
      },
      width: 120,
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '此项是必填项',
      //     },
      //     {
      //       validator: (_, value) => {
      //         if (value <= 0) {
      //           return Promise.reject(new Error('不能为0'));
      //         }
      //         return Promise.resolve();
      //       },
      //       message: '价格不能为0',
      //     },
      //   ],
      // },
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: 150,
      render: (_, record) => {
        return [
          <a
            key="edit"
            onClick={() => {
              actionRef.current?.startEditable(record.id);
            }}
          >
            修改
          </a>,
          <a
            key="delete"
            onClick={() => {
              const dataSource2 = dataSource.filter((item) => record.id !== item.id);
              setDataSource(dataSource2);
              onChange?.(dataSource2);
            }}
          >
            删除
          </a>,
          <a
            key="copy"
            onClick={() => {
              const id = `new_${Date.now()}`;
              dataSource.push({ ...record, id });
              setDataSource(Object.assign([], dataSource));
              editableKeys.push(id);
              setEditableRowKeys(editableKeys);
            }}
          >
            复制
          </a>,
        ];
      },
    },
  ];
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    validate: () => {
      return editForm
        .validateFields()
        .then((values) => {
          return true;
        })
        .catch((errorInfo) => {
          return false;
        });
    },
    getData: () => dataSource,
    getForm: () => editForm.getFieldsValue(),
    editableKeys,
  }));

  return (
    <div className="service-record-rent">
      <div className="header">
        <div className="title">2.物品信息</div>
      </div>
      <Divider style={{ margin: '10px 0 0' }} />
      <EditableProTable<any, COMMON.PageParams>
        rowKey="id"
        options={false}
        bordered
        actionRef={actionRef}
        search={false}
        pagination={false}
        value={dataSource}
        className="item-pro-table"
        
        onChange={(values) => {
          setDataSource(values);
        }}
        columns={columns}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          record: () => ({
            id: `new_${Date.now()}`,
            goods_num: 1,
            cycle_num: 1,
          }),
        }}
        editable={{
          form: editForm,
          // type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [
              defaultDoms.save,
              defaultDoms.delete /*<a key="copy" onClick={() => {
              const id = `new_${Date.now()}`;
              console.log('row', row);
              dataSource.push({ ...row, id });
              setDataSource(Object.assign([], dataSource));
              editableKeys.push(id);
              setEditableRowKeys(editableKeys);
            }}>复制</a>*/,
            ];
          },
          onChange: setEditableRowKeys,
          onSave: async (key, record) => {
            let data = dataSource.find((item) => item.id === key);
            let index = dataSource.findIndex((item) => item.id === key);
            data = Object.assign({}, data, record);
            const dataSource2: any[] = [].concat(dataSource);
            dataSource2[index] = data;

            onChange?.(dataSource2);
          },

          onDelete: async (key, row) => {
            const dataSource2 = dataSource.filter((item) => item.id !== key);
            console.log(dataSource2);
            onChange?.(dataSource2);
          },
          // onValuesChange: (record, recordList) => {
          //   setDataSource(recordList);
          // },
        }}
        scroll={{
          x: 1000,
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.id === clickRow ? 'tableRowClick' : ''
        }}
      />
    </div>
  );
});
export default ItemInfo;
